package com.example.player_plugin;

import android.content.Context;

import androidx.annotation.NonNull;

import com.easefun.polyvsdk.PolyvSDKClient;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/** PlayerPlugin */
public class PlayerPlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;

  private Context context;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "plugins.polyv/util");
    channel.setMethodCallHandler(this);
    context = flutterPluginBinding.getApplicationContext();
    BinaryMessenger messenger = flutterPluginBinding.getBinaryMessenger();
    NativePolyvVideoViewFactory factory = new NativePolyvVideoViewFactory(messenger);
    flutterPluginBinding
            .getPlatformViewRegistry()
            .registerViewFactory("plugins.polyv/video", factory);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("playerConfig")) {
      String config = call.argument("config");
      String aesKey = call.argument("aesKey");
      String iv = call.argument("iv");
      PolyvSDKClient client = PolyvSDKClient.getInstance();
      client.settingsWithConfigString(config, aesKey, iv);
      client.initSetting(context);
    }
    else if (call.method.equals("accountConfig")) {
      PolyvSDKClient client = PolyvSDKClient.getInstance();
      String userID = call.argument("userID");
      String secretKey = call.argument("secretKey");
      String readToken = call.argument("readToken");
      String writeToken = call.argument("writeToken");
      boolean success = client.settingsWithUserid(userID, secretKey, readToken, writeToken);
      result.success(success);
    }
    else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }
}
